package login

import org.apache.shiro.grails.ConfigUtils
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.web.util.SavedRequest
import org.apache.shiro.web.util.WebUtils
import audit.LoginLog

class AuthController {
    def shiroSecurityManager

    def index = { redirect(action: "login", params: params) }

    def login = {
        if(SecurityUtils.subject.isAuthenticated()){
			def targetUri = params.targetUri ?: "/main"
			redirect(uri: targetUri)
        }
		else{
			return [ username: params.username, rememberMe: (params.rememberMe != null), targetUri: params.targetUri ]
    	}
	}
			

    def signIn = {
		def authToken = new UsernamePasswordToken(params.username, params.password as String)
		if (params.rememberMe) {
            authToken.rememberMe = true
        }
        
        // If a controller redirected to this page, redirect back
        // to it. Otherwise redirect to the root URI.
        def targetUri = params.targetUri ?: "/"
        
        // Handle requests saved by Shiro filters.
        def savedRequest = WebUtils.getSavedRequest(request)
        if (savedRequest) {
            targetUri = savedRequest.requestURI - request.contextPath
            if (savedRequest.queryString) targetUri = targetUri + '?' + savedRequest.queryString
        }
        
        try{
            // Perform the actual login. An AuthenticationException
            // will be thrown if the username is unrecognised or the
            // password is incorrect.
            SecurityUtils.subject.login(authToken)
			LoginLog loginLog = new LoginLog(user: User.findByUsername(authToken.username)).save(flush:true)
			
            log.info "Redirecting to '${targetUri}'."
            redirect(uri: targetUri)
        }
        catch (AuthenticationException ex){
            log.info "Authentication failure for user '${params.username}'."
            flash.message = message(code: "login.failed")
            def m = [ username: params.username ]
            if (params.targetUri) {
                m["targetUri"] = params.targetUri
            }
            // Now redirect back to the login page.
            redirect(action: "login", params: m)
        }
    }

    def signOut = {
        // Log the user out of the application.
        def principal = SecurityUtils.subject?.principal
        SecurityUtils.subject?.logout()
        // For now, redirect back to the home page.
        if (ConfigUtils.getCasEnable() && ConfigUtils.isFromCas(principal)) {
            redirect(uri:ConfigUtils.getLogoutUrl())
        }else {
            redirect(uri: "/")
        }
        ConfigUtils.removePrincipal(principal)
    }

    def unauthorized = {
        flash.message = message(code:'default.notPermitted.label',default:"You don't have permission to access the given address")
		redirect(controller:'main')
    }
}
